<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Lib;
use app\admin\controller\sensitive\Wordscategory;
use app\admin\controller\WebsiteArea;
use fast\Arr;
use think\Db;
use think\Model;
use MDword\WordProcessor;
use Hisune\EchartsPHP\ECharts;
use think\Session;

class Website extends Api
{
	
	
	protected $noNeedLogin = ['report', 'report_word', 'saveImg'];
	protected $noNeedRight = ['*'];
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-6 11:48
	 * @Introduce: 网站列表
	 * @throws \think\exception\DbException
	 */
	public function List()
	{
//		if (!$this->request->isGet()) {
//			$this->error('请求方法不允许', null, 405);
//		}
		
		$this->request->filter(['strip_tags', 'trim']);
		
		$where       = [];
		$filing_type = $this->request->param('filing_type');
		if ($filing_type) {
			$where['filing_type'] = $filing_type;
		}

		
		$whereLike    = [];
		$website_name = $this->request->param('website_name');
		if ($website_name) {
			$whereLike = ['website_name', 'like', "%$website_name%"];
		}
        $where['user_id'] = $this->auth->id;

		$model = new \app\common\model\Website();
		
		$field         = 'id, filing_type, website_name, website_domain, filing_license_no, sponsor, place_business, office_address, access_point, area, ip_address, ip_location, detectioned_at';
		$listFindModel = $model->field($field)->where($where);

		if ($website_name) {
			$listFindModel->where($whereLike[0], $whereLike[1], $whereLike[2]);
		}
		
		$listFindModel->with(['viocontent' => function ($query) {
			$query->field('id, title, link, word as sensitive_words, category as sensitive_words_category, website_id');
		}]);
		
		$list = $listFindModel->paginate(10);
		
		$result = ["total" => $list->total(), "rows" => $list->items()];
		
		$this->success('请求成功', $result);
		
	}

		/**
		 * @Author   : crafters@qq.com
		 * @DateTime : 2022-3-6 16:31
		 * @Introduce: 网站添加
		 */
		 function Add()
		{
			
			if (!$this->request->isPost()) {
				$this->error('请求方法不允许', null, 405);
			}
			
			$data = $this->processWebsiteData();
            $str = str_replace('http://','',$data['website_domain']);
            $str = str_replace('https://','',$str);
            $str = substr($str,0,strlen($str)-1);
            $ip = gethostbyname($str);
            $urldata = $this->getaddress($ip);
            if($urldata != false &&$urldata['ret'] == 'ok'){
                $data['province'] = $urldata['data'][1];
                $data['city'] = $urldata['data'][2];
                $data['areas'] = $urldata['data'][3];
                $data['access_point'] = $urldata['data'][1].$urldata['data'][2].$urldata['data'][3];
                if($urldata['data'][0] != '中国'){
                    $data['is_abroad'] = '2';
                }else{
                    $data['is_abroad'] = '1';
                }
            }
            $data['user_id'] = $this->auth->id;
			$result = Db::name('website')->insert($data);
			
			if (!$result) {
				$this->error('新增失败');
			}
			
			$this->success('新增成功');
		}

        public function getaddress($ip){
//        https://user.ip138.com   官网
//            if($queryIP == '127.0.0.1'){
//                $queryIP = '120.79.188.10';
//            }
            /***  $queryIP 请求地址的IP*/
//        https://api.ip138.com/ip/?ip=58.16.180.3&datatype=jsonp&token=cc87f3c77747bccbaaee35006da1ebb65e0bad57
//            $url = 'https://api.ip138.com/ip/?ip='.$queryIP.'&datatype=jsonp&token=20a4b0309595f63a103afa55dc3cd93f';
//            var_dump($ip);die;
//            $ip = '54.125.252.15';
                $datatype = 'jsonp';
                $url = 'http://api.ip138.com/ip/?ip=' . $ip . '&datatype=' . $datatype;
                $header = array('token:20a4b0309595f63a103afa55dc3cd93f');
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
                $handles = curl_exec($ch);
                curl_close($ch);
                if($handles !== false){
                    return \GuzzleHttp\json_decode($handles,true);
                }else{
                    return false;
                }
        }

		/**
		 * @Author   : crafters@qq.com
		 * @DateTime : 2022-3-6 16:30
		 * @Introduce: 网站添加
		 * @throws \think\Exception
		 * @throws \think\exception\PDOException
		 */
		public function Update()
		{
			
			if (!$this->request->isPost()) {
				$this->error('请求方法不允许', null, 405);
			}
			
			$id = $this->request->param('id');
			
			if (!$id) {
				$this->error('请填写id');
			}
			
			$data = $this->processWebsiteData($id);
            $str = str_replace('http://','',$data['website_domain']);
            $str = str_replace('https://','',$str);
            $str = substr($str,0,strlen($str)-1);
            $ip = gethostbyname($str);
            $urldata = $this->getaddress($ip);
            if($urldata != false &&$urldata['ret'] == 'ok'){
                $data['province'] = $urldata['data'][1];
                $data['city'] = $urldata['data'][2];
                $data['areas'] = $urldata['data'][3];
                $data['access_point'] = $urldata['data'][1].$urldata['data'][2].$urldata['data'][3];
                if($urldata['data'][0] != '中国'){
                    $data['is_abroad'] = '2';
                }else{
                    $data['is_abroad'] = '1';
                }
            }
            $data['user_id'] = $this->auth->id;
			$result = Db::name('website')->where(['id' => $id])->update($data);
			
			
			$this->success('更新成功');
        }
	
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-6 11:47
	 * @Introduce: 网站删除
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function Del()
	{
		
		if (!$this->request->isPost()) {
			$this->error('请求方法不允许', null, 405);
		}
		
		$ids = $this->request->post("ids");
		
		if (!$ids) {
			$this->error('id不能为空');
		}
		
		$delIds = [];
		foreach (explode(',', $ids) as $k => $v) {
			$delIds = array_merge($delIds, [$v]);
		}
		$delIds = array_unique($delIds);
		
		$isDel = Db::name('website')->where(['user_id'=>$this->auth->id])->where('id', 'in', $delIds)->delete();
		if (!$isDel) {
			$this->error('删除失败');
		}
		
		$this->success('删除成功');
		
	}
	
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-6 11:47
	 * @Introduce: 网站分类列表
	 * @throws \think\exception\DbException
	 */
	public function Category()
	{
//		if (!$this->request->isGet()) {
//			$this->error('请求方法不允许', null, 405);
//		}
		
		$list = Db::name('website_category')->field('id, cate_name')->where([])->paginate(10);
		
		$result = ["total" => $list->total(), "rows" => $list->items()];
		
		$this->success('请求成功', $result);
	}
	
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-7 18:33
	 * @Introduce: 网址库
	 * @throws \think\exception\DbException
	 */
	public function Lib()
	{
//
//		if (!$this->request->isGet()) {
//			$this->error('请求方法不允许', null, 405);
//		}
		
		$where = [];
		
		$list = Db::name('website_lib')->alias('wl')
            ->join('website w','w.id=wl.belong_website')
            ->field('wl.*')
            ->where(['w.user_id'=>$this->auth->id])
            ->where($where)
            ->paginate(10);
		
		$result = ["total" => $list->total(), "rows" => $list->items()];
		
		$this->success('请求成功', $result);
		
	}
	
	
	public function EditLib()
	{
		if (!$this->request->isPost()) {
			$this->error('请求方法不允许', null, 405);
		}
		
		$this->request->filter(['strip_tags', 'trim']);
		
		$id = $this->request->param('id');
		
		
		//网址标示，链接，抓取时间，快照地址，响应代码，所属网站
		$website_label     = $this->request->param('website_label');
		$website_link      = $this->request->param('website_link');
		$grab_time         = $this->request->param('grab_time');
		$snapshot_address  = $this->request->param('snapshot_address');
		$response_code     = $this->request->param('response_code');
		$website_domain_id = $this->request->param('website_domain_id');
		
		$data = [
			'website_label'     => $website_label,
			'website_link'      => $website_link,
			'grab_time'         => $grab_time,
			'snapshot_address'  => $snapshot_address,
			'response_code'     => $response_code,
			'website_domain_id' => $website_domain_id,
		];
		
		$website = new Lib();
		
		$website->save($data, ['id' => $id]);
		$this->success('更新成功');
		
	}
	
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-11 15:54
	 * @Introduce: 删除网址库
	 * @throws \think\Exception
	 * @throws \think\exception\PDOException
	 */
	public function DelLib()
	{
		if (!$this->request->isPost()) {
			$this->error('请求方法不允许', null, 405);
		}
		
		$ids = $this->request->post("ids");
		if (!$ids) {
			$this->error('id不能为空');
		}
		
		$delIds = [];
		foreach (explode(',', $ids) as $k => $v) {
			$delIds = array_merge($delIds, [$v]);
		}
		$delIds = array_unique($delIds);
		
		
		$isDel = Db::name('website_lib')->where('id', 'in', $delIds)->delete();
		
		if (!$isDel) {
			$this->error('删除失败');
		}
		
		$this->success('删除成功');
		
	}
	
	
	/**
	 * @Author   : crafters@qq.com
	 * @DateTime : 2022-3-9 17:48
	 * @Introduce: 地区列表接口
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function Area()
	{
		$result = Db::name('website_area')->field('id, area_name')->select();
		$this->success('请求成功', ['list' => $result]);
	}
	
	/**
	 * @Author   : yimo
	 * @DateTime : 2022年3月31日
	 * @Introduce: 报告生成接口
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function report()
	{
		$data = [];
		
		$domain = request()->domain();
		$param = request()->param();
		$cookie = request()->header('Cookie');
		$where = [];
        $vioWhere = [];
        $query = [];
        if (
            !empty($param['date_start'])
            &&\think\Validate::dateFormat($param['date_start'],'Y-m-d')
            &&!empty($param['date_end'])
            &&\think\Validate::dateFormat($param['date_end'],'Y-m-d') 
            && strtotime($param['date_end']) >= strtotime($param['date_start'])
        ) {
            $where['created_at']=[['egt',strtotime($param['date_start']) ],['elt',strtotime($param['date_end'])+3600*24-1 ] ];
            $vioWhere['a.create_time']=[['egt',strtotime($param['date_start']) ],['elt',strtotime($param['date_end'])+3600*24-1 ] ];
        	$query['date_start'] = $param['date_start'];
        	$query['date_end'] = $param['date_end'];
        }else{
        	$param['date_start'] = strtotime(date('Y-m-d'));
        	$param['date_end'] = strtotime(date('Y-m-d'));
        }
        if (
            isset($param['sensitive_words_cate_id'])
            &&\think\Validate::is($param['sensitive_words_cate_id'],'number')
        ) {
            $where['filing_type']= $param['sensitive_words_cate_id'];
            $vioWhere['w.filing_type']= $param['sensitive_words_cate_id'];
            $query['sensitive_words_cate_id'] = $param['sensitive_words_cate_id'];
        }

        $query['user_id'] = $this->auth->id;

		$url = $domain."/index/index/chartpic?".http_build_query($query);
		// $client = new \GuzzleHttp\Client();
		// $res = $client->request('GET', $url, $param);
		// echo $res->getStatusCode();
		// "200"
		// echo $res->getHeader('content-type');
		// 'application/json; charset=utf8'
		// echo $res->getBody();
		// exit;

		//初始化一个 cURL 对象
		$ch  = curl_init();
		//设置你需要抓取的URL
		curl_setopt($ch, CURLOPT_URL, $url);
		// 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//是否获得跳转后的页面
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt ($ch, CURLOPT_COOKIE , $cookie );//使用cookie

		$cur_data = curl_exec($ch);
		curl_close($ch);
        // var_dump( $cur_data,$url);exit;
        $where['user_id'] = $this->auth->id;
		$site_list = db()->name('website')->where($where)->select();
		$data['website_count'] = count($site_list);
		$site_category = db()->name('website_category')->select();
		// $filing_type = [];
		// foreach ($site_category as $value) {
		// 	$filing_type[$value['id']] = $value['cate_name'];
		// }
		$data['site_name'] = config('site.name');
        $data['date_start'] = date('Y年m月d日',strtotime($param['date_start']));
        $data['date_end'] = date('Y年m月d日',strtotime($param['date_end'] ));
		$data['request_success_count'] = 0;//正常访问
		$data['request_failed_count'] = 0;//无法访问
		$data['within_border_count'] = 0;//境内接入
		$data['oversea_count'] = 0;//境外接入
		$data['group_count'] = 0;//法人备案
		$data['personal_count'] = 0;//个人备案
		$data['local_access_count'] = 0;//本地接入 
		$data['local_access_ratio'] = 0;//本地与境内接入占比
		$data['winthin_other_ratio'] = 0;//境内其他地区占比

		$data['table_abroad'] = [];//开封市违规境外接入网站信息表
		$data['table_cause'] = [];//开封市党政机关、事业单位存在问题网站信息表 
		$data['table_access'] = [];//开封市无法打开、跳转、被“挂马”网站信息表 
		$data['table_sensitive'] = [];//开封市属地违规网站信息表
		$data['oversea_and_failed_count'] = 0;//境外及无法访问
		$data['oversea_and_failed_ratio'] = 0;//境外及无法访问占比

		
		$vioWebsite = db()
            ->name('vio_content_sensitive_words')
            ->alias('a')
            ->join('sensitive_words_category b', 'a.sensitive_words_category_id = b.id','left')
            ->field('a.website_id,b.cate_name')
            ->where('a.website_id','in',array_column($site_list, 'id') )
            ->group('a.website_id');
            // 
        if (!empty($vioWhere['a.create_time'])) {
        	$websiteWhere = [
        		'a.create_time'=>$vioWhere['a.create_time']
        	];
        	$vioWebsite->where($websiteWhere);
        }
        $vioWebsite = $vioWebsite
        // ->where('a.website_id','=',0 )
        // ->fetchSql(true)
        ->select();
        $vioWebsite = array_column($vioWebsite, null,'website_id');

		foreach($site_list as $value) {

			if (isset($vioWebsite[$value['id']])) {
				//开封市属地违规网站信息表
				$data['table_sensitive'][] = [
					'tb_sensitive_name'=>$value['website_name'],
					'tb_sensitive_host'=>$value['website_domain'],
					'tb_sensitive_type'=>$vioWebsite[$value['id']]['cate_name'],
					'tb_sensitive_ip'=>$value['ip_address'],
					'tb_sensitive_num'=>$value['filing_license_no'],
					'tb_sensitive_user'=>$value['sponsor'],
					'tb_sensitive_area'=>$value['access_point'],
					'tb_sensitive_login'=>$value['ip_location'],
				];
			}

			if (isset($value['is_access'])) {
				if((int)$value['is_access'] == 1) {//正常访问
					$data['request_success_count'] += 1;
				} else if ((int)$value['is_access'] == 0){//无法访问
					$data['request_failed_count'] += 1;
					
					//开封市无法打开、跳转、被“挂马”网站信息表 
					$data['table_access'][] = [
						'tb_access_name'=>$value['website_name'],
						'tb_access_host'=>$value['website_domain'],
						'tb_access_type'=>$vioWebsite[$value['id']]['cate_name'],
						'tb_access_ip'=>$value['ip_address'],
						'tb_access_num'=>$value['filing_license_no'],
						'tb_access_user'=>$value['sponsor'],
						'tb_access_area'=>$value['access_point'],
						'tb_access_login'=>$value['ip_location'],
					];
				}
			}
			if ((isset($value['is_access']) && (int)$value['is_access'] == 0) || (isset($value['is_abroad'])&&  (int)$value['is_abroad'] == 2)  ) {
				$data['oversea_and_failed_count'] += 1;
			}

			if (isset($value['is_abroad'])) {
				if((int)$value['is_abroad'] == 1) {//境内接入
					$data['within_border_count'] += 1;
				} else if ((int)$value['is_abroad'] == 2){//境外接入
					$data['oversea_count'] += 1;
					if (isset($vioWebsite[$value['id']])) {
						//开封市违规境外接入网站信息表
						$data['table_abroad'][] = [
							'tb_abroad_name'=>$value['website_name'],
							'tb_abroad_host'=>$value['website_domain'],
							'tb_abroad_type'=>$vioWebsite[$value['id']]['cate_name'],
							'tb_abroad_ip'=>$value['ip_address'],
							'tb_abroad_num'=>$value['filing_license_no'],
							'tb_abroad_user'=>$value['sponsor'],
							'tb_abroad_area'=>$value['access_point'],
							'tb_abroad_login'=>$value['ip_location'],
						];
					}

				}
			}
			if (isset($value['filing_type'])) {
				if((int)$value['filing_type'] == 3) {//法人备案
					$data['group_count'] += 1;
				} else if ((int)$value['filing_type'] == 4){//个人备案
					$data['personal_count'] += 1;
				}else if (in_array((int)$value['filing_type'], [2,5]) ){
					//2 党政机关备案
					//5 事业单位备案
					$data['personal_count'] += 1;
					if (isset($vioWebsite[$value['id']])) {
						//开封市党政机关、事业单位存在问题网站信息表
						$data['table_cause'][] = [
							'tb_cause_name'=>$value['website_name'],
							'tb_cause_host'=>$value['website_domain'],
							'tb_cause_type'=>$vioWebsite[$value['id']]['cate_name'],
							'tb_cause_ip'=>$value['ip_address'],
							'tb_cause_num'=>$value['filing_license_no'],
							'tb_cause_user'=>$value['sponsor'],
							'tb_cause_area'=>$value['access_point'],
							'tb_cause_login'=>$value['ip_location'],
						];
					}
				}
			}
			//本地接入 
			if (isset($value['province'])&&$value['province'] == '河南') {
				$data['local_access_count'] += 1;
			}

		}
		//开封市违规境外接入网站信息表
		if (empty($data['table_abroad'])) {
			$data['table_abroad'][] = [
				'tb_abroad_name'=>'',
				'tb_abroad_host'=>'',
				'tb_abroad_type'=>'',
				'tb_abroad_ip'=>'',
				'tb_abroad_num'=>'',
				'tb_abroad_user'=>'',
				'tb_abroad_area'=>'',
				'tb_abroad_login'=>'',
			];
		}
		//开封市党政机关、事业单位存在问题网站信息表
		if (empty($data['table_cause'])) {
			$data['table_cause'][] = [
				'tb_cause_name'=>'',
				'tb_cause_host'=>'',
				'tb_cause_type'=>'',
				'tb_cause_ip'=>'',
				'tb_cause_num'=>'',
				'tb_cause_user'=>'',
				'tb_cause_area'=>'',
				'tb_cause_login'=>'',
			];
		}
		//开封市无法打开、跳转、被“挂马”网站信息表
		if (empty($data['table_access'])) {
			$data['table_access'][] = [
				'tb_access_name'=>'',
				'tb_access_host'=>'',
				'tb_access_type'=>'',
				'tb_access_ip'=>'',
				'tb_access_num'=>'',
				'tb_access_user'=>'',
				'tb_access_area'=>'',
				'tb_access_login'=>'',
			];
		}
		//开封市属地违规网站信息表
		if (empty($data['table_sensitive'])) {
			$data['table_sensitive'][] = [
				'tb_sensitive_name'=>'',
				'tb_sensitive_host'=>'',
				'tb_sensitive_type'=>'',
				'tb_sensitive_ip'=>'',
				'tb_sensitive_num'=>'',
				'tb_sensitive_user'=>'',
				'tb_sensitive_area'=>'',
				'tb_sensitive_login'=>'',
			];
		}
		if ($data['within_border_count']) {
			//本地与境内接入占比
			$data['local_access_ratio'] =  intval($data['local_access_count'] / $data['within_border_count'] * 100);
			//境内其他地区占比
			$data['winthin_other_ratio'] = intval(($data['within_border_count'] - $data['local_access_count']) / $data['within_border_count'] * 100);
		}
		if ($data['oversea_and_failed_count']) {
			//境外及无法访问占比
			$data['oversea_and_failed_ratio'] =  intval($data['oversea_and_failed_count'] / $data['website_count'] * 100);
		}
		$data['sensitive_count'] = '';// 敏感信息
		// $data['government_count'] = 0;// 党政机关网站数量

		// request_success_count
		// $vio_content = db()->name('vio_content')->field('id, main, title, link, category, word, right_word, website_lib_id, website_id')->select();
		$vio = db()
            ->name('vio_content_sensitive_words')
            ->alias("a")
            ->join('sensitive_words_category b', 'a.sensitive_words_category_id = b.id','left')
            ->join('vio_content vc', 'a.vio_content_id = vc.id','left')
            ->join('website w', 'vc.website_id = w.id','left')
            ->field('b.cate_name, count(*) as count')
            ->group('sensitive_words_category_id')
            ->order('count desc')
            ->where($vioWhere)
            ->limit(4)
            ->select();
        $access_category_data_list = [];
        $sensitive_count = '%s家网站涉及%s类信息；';
        foreach ($vio as $value) {
        	$data['sensitive_count'] .= sprintf($sensitive_count,$value['count'],$value['cate_name']);
        }

		// 取出图片
		$img_name_list = ['with_site', 'media', 'abroad', 'access_category'];
		foreach($img_name_list as $key => $value) {
			$data['report_img'][$value] = ROOT_PATH . 'public' . DS .'uploads' . DS . 'report_pic' . DS . Session::get($value);
		}
        
		$file_path = $this->report_word($data);
		$this->success('',$file_path);
	}

	/**
	 * 只有网站
	 * vio 违规信息
	 * website_lib 某网站页面的链接
	 * 
	 * 网站总数 	website_count
	 * 正常访问 	request_success_count
	 * 无法访问 	request_failed_count
	 * 法人备案		group_count
	 * 个人备案		personal_count
	 * 境内接入 	within_ border_count
	 * 境外接入 	oversea_count
	 * 
	 * 本地接入 	local_access_count
	 * 本地与境内接入占比 	local_access_count
	 * 境内其他地区占比  	winthin_other_ratio
	 * 境外及无法访问 		oversea_and_failed_count
	 * 党政机关访问失败 	government_fialed_count
	 * 党政机关网站数量 	government_count
	 * 境外及无法访问占比 	oversea_and_failed_ratio
	 * 
	 * 表述错误 	misstatement_count
	 * 时政敏感 	sensor_count
	 * 反动类 		reactionary_count
	 * 民族宗教 	religions_count
	 * 
	 * 页面总数		website_lib_count
	 */

	/**
	 * 生成报表
	 */
	public function report_word($data) {

		$TemplateProcessor = new WordProcessor();
		$template = ROOT_PATH . 'public' . DS . 'file_template' . DS. 'report_template.docx';
		if(!file_exists($template)) {
			return('模板文件不存在,生成失败');
		}
		$TemplateProcessor->load($template);

		// 插入图片
		if ($data['report_img']) {
			// var_dump($data['report_img']);
			foreach($data['report_img'] as $key => $value) {
				$TemplateProcessor->setImageValue($key, $value);
			}
			// unset($data['report_img']);
		}
		// 插入文字
		foreach($data as $key => $value) {
			$TemplateProcessor->setValue($key, $value);
		}

		//开封市违规境外接入网站信息表
		if (count($data['table_abroad']) > 1) {
			//克隆并复制

			$TemplateProcessor->clones('tb_abroad_item', count($data['table_abroad']));

			foreach ($data['table_abroad'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k.'#'.$key, $v);
				}
			}
			// unset($data['report_img']);
		}else{
			foreach ($data['table_abroad'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k, $v);
				}
			}
		}
		//开封市党政机关、事业单位存在问题网站信息表
		if (count($data['table_cause']) > 1 ) {
			//克隆并复制

			$TemplateProcessor->clones('tb_cause_item', count($data['table_cause']));

			foreach ($data['table_cause'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k.'#'.$key, $v);
				}
			}
			// unset($data['report_img']);
		}else{
			foreach ($data['table_cause'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k, $v);
				}
			}
		}
		//开封市无法打开、跳转、被“挂马”网站信息表
		if (count($data['table_access']) > 1 ) {
			//克隆并复制

			$TemplateProcessor->clones('tb_access_item', count($data['table_access']));

			foreach ($data['table_access'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k.'#'.$key, $v);
				}
			}
			// unset($data['report_img']);
		}else{
			foreach ($data['table_access'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k, $v);
				}
			}
		}
		//开封市属地违规网站信息表
		if (count($data['table_sensitive']) > 1 ) {
			//克隆并复制

			$TemplateProcessor->clones('tb_sensitive_item', count($data['table_sensitive']));

			foreach ($data['table_sensitive'] as $key => $value) {
				foreach ($value as $k => $v) {
					// dump($k.'#'.$key.$v);
					//插入文字
					$TemplateProcessor->setValue($k.'#'.$key, $v);
				}
			}
			// exit;
			// unset($data['report_img']);
		}else{
			foreach ($data['table_sensitive'] as $key => $value) {
				foreach ($value as $k => $v) {
					//插入文字
					$TemplateProcessor->setValue($k, $v);
				}
			}
		}

		//保存
		$fix = date('YmdHis').rand(1000,9999); 
		$file_path = DS .'uploads' . DS . 'report'. DS . 'report'. $fix .'.docx';        

		$rtemplate = ROOT_PATH . 'public' .  $file_path;
		 if(is_dir(ROOT_PATH . 'public' . DS .'uploads' . DS . 'report' ) == false){
            mkdir(ROOT_PATH . 'public' . DS .'uploads' . DS . 'report' , 0777, true);
        }
		$TemplateProcessor->saveAs($rtemplate);
		
		

		$res_ = ['code'=>1, 'msg'=>'生成成功', $data=''];
		return  request()->domain() .$file_path;
	}

	public function saveImg()
	{
		$param = $this->request->param();
		$picInfo = $param['pics'];
		foreach($picInfo as $key => $value) {
			$streamFileRand = date('YmdHis').rand(1000,9999); 
			$picType ='.png';//图片后缀
			$streamFilename = ROOT_PATH . 'public' . DS .'uploads' . DS . 'report_pic' . DS .$streamFileRand .$picType; //图片保存地址
			if(is_dir(ROOT_PATH . 'public' . DS .'uploads' . DS . 'report_pic' ) == false){
                mkdir(ROOT_PATH . 'public' . DS .'uploads' . DS . 'report_pic' , 0777, true);
            }
			preg_match('/(?<=base64,)[\S|\s]+/',$value,$picInfoW);//处理base64文本
			file_put_contents($streamFilename,base64_decode($picInfoW[0]));//文件写入

			Session::set($key, $streamFileRand .$picType);
		}
	}
	
}
